import React, {useState, useMemo, useEffect} from 'react';
import {Table, Button, Modal, Form, Input, Space, message, Input as AntInput, Select} from 'antd';
import {
    addClassInfo,
    batchDeleteClassInfo,
    deleteClassInfo,
    getClassInfo,
    updateClassInfo
} from "../../api/classInfo.js";
import ClassModal from "./component/ClassModal.jsx";
import StudentInClassModal from "./component/StudentInClassModal.jsx";

const ClassPage = () => {
    const [form] = Form.useForm();
    const [data, setData] = useState([]);

    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editingRecord, setEditingRecord] = useState(null);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [searchKeyword, setSearchKeyword] = useState('');
    const [loading, setLoading] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [checkClass,setCheckClass] = useState(null);


    const selectedRecords = useMemo(() =>
            data.filter(item => selectedRowKeys.includes(item.id)),
        [data, selectedRowKeys]
    );

    useEffect(() => {
        fetchClassInfo();
    }, []);
    const fetchClassInfo = async () => {
        setLoading(true);
        try {
            const res = await getClassInfo(null);
            setData(res.data);
        } catch (error) {
            message.error('获取班级列表失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    // ========== 表格配置 ==========
    const rowSelection = {
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys) => {
            setSelectedRowKeys(selectedRowKeys);
        },
    };

    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            render: (_, record, index) => index + 1,
        },
        {
            title: '班级名称',
            dataIndex: 'className',
            align: 'center',
            key: 'className'
        },
        {
            title: '班级代码',
            dataIndex: 'classCode',
            align: 'center',
            key: 'classCode'
        },
        {
            title: '所属学院',
            dataIndex: 'academyName',
            align: 'center',
            key: 'academyName'
        },
        {
            title: '所属专业',
            dataIndex: 'specialtyName',
            align: 'center',
            key: 'specialtyName'
        },
        {
            title: '班级导师',
            dataIndex: 'teacherName',
            align: 'center',
            key: 'teacherName'
        },
        {
            title: '年级',
            dataIndex: 'grade',
            key: 'grade',
            align: 'center',
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            render: (_, record) => (
                <Space size="middle">
                    <Button type="link" onClick={() => handleCheckStudent(record)}>
                        查看班级学生
                    </Button>
                    <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
                    <Button type="link" danger onClick={() => handleDelete(record.id)}>删除</Button>
                </Space>
            )
        }
    ];

    const handleCheckStudent = (record) => {
        setCheckClass(record);
        setModalVisible(true);
    }

    const handleDelete = (id) => {
        Modal.confirm({
            title: '确认删除该班级信息？',
            onOk: () => {
                deleteClass({classId: id})
            }
        });
    };

    const handleBatchDelete = () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请至少选择一条记录');
            return;
        }

        Modal.confirm({
            title: '确认删除选中的班级信息？',
            onOk: () => {
                batchDeleteClass({
                    ids: selectedRowKeys
                })
                setSelectedRowKeys([]);
            }
        });
    };

    const handleEdit = (record) => {
        setEditingRecord(record);
        form.setFieldsValue(record);
        setIsModalVisible(true);
    };

    const handleAdd = () => {
        setEditingRecord(null);
        form.resetFields();
        setIsModalVisible(true);
    };

    const handleOk = (values) => {
            if (editingRecord) {
                updateClass({
                    classId: editingRecord.classId,
                    specialtyId: values.specialtyId,
                    teacherId: values.teacherId,
                    className: values.className,
                    classCode: values.classCode
                });
            } else {
                addClass({
                    specialtyId: values.specialtyId,
                    teacherId: values.teacherId,
                    className: values.className,
                    classCode: values.classCode,
                    grade: values.grade
                });
            }
            setIsModalVisible(false);
            form.resetFields();
    };

    const handleCancel = () => {
        setIsModalVisible(false);
        form.resetFields();
    };

    const addClass = async (data) => {
        try {
            const res = await addClassInfo(data);
            if (res.code === 200) {
                message.success("新增成功")
                fetchClassInfo();
            }
        } catch (error) {
            message.error('新增失败');
            console.error(error);
        }
    }
    const updateClass = async (data) => {
        try {
            const res = await updateClassInfo(data);
            if (res.code === 200) {
                message.success("修改成功")
                fetchClassInfo();
            }
        } catch (error) {
            message.error('修改失败');
            console.error(error);
        }
    }
    const deleteClass = async (data) => {
        try {
            const res = await deleteClassInfo(data);
            if (res.code === 200) {
                message.success("删除成功")
                fetchClassInfo();
            }
        } catch (error) {
            message.error('删除失败');
            console.error(error);
        }
    }
    const batchDeleteClass = async (data) => {
        try {
            const res = await batchDeleteClassInfo(data);
            if (res.code === 200) {
                message.success("批量删除成功")
                fetchClassInfo();
                setSelectedRowKeys([]);
            }
        } catch (error) {
            message.error('批量删除失败');
            console.error(error);
        }
    }

    return (
        <div style={{padding: 14}}>
            <div style={{
                marginBottom: 16,
                display: 'flex',
                justifyContent: 'space-between',
                flexWrap: 'wrap',
                gap: 8
            }}>
                <Space>
                    <Button type="primary" onClick={handleAdd}>新增班级</Button>
                    <Button danger disabled={selectedRowKeys.length === 0} onClick={handleBatchDelete}>
                        批量删除
                    </Button>
                </Space>

                <Space>
                    <AntInput.Search
                        placeholder="请输入班级名称"
                        value={searchKeyword}
                        onChange={(e) => setSearchKeyword(e.target.value)}
                        style={{width: 250}}
                        allowClear
                    />
                </Space>
            </div>

            <Table
                rowKey="id"
                dataSource={data}
                columns={columns}
                rowSelection={rowSelection}
                loading={loading}
            />

            <StudentInClassModal
                visible={modalVisible}
                onCancel={() => setModalVisible(false)}
                checkClass={checkClass}
            />

            <ClassModal
                visible={isModalVisible}
                onOk={handleOk}
                onCancel={handleCancel}
                editingRecord={editingRecord}
            />
        </div>
    );
};

export default ClassPage;